#include "heap.h"
#include <stdio.h>

static int heap_start, heap_end;
static union uKernel_Heap{
	volatile uint_32 ulDummy;
	uint_8 heap[HEAP_SIZE];
} xHeap;
void heapInit()
{	
	uint_32 i;
	for (i = 0; i < HEAP_SIZE; i++){
		xHeap.heap[i] = 0;
	}
}


void *portMalloc(uint_8 sizeRequested)
{
	void *ret;
	if (heap_end + sizeRequested > HEAP_SIZE) {
		if ((heap_end + sizeRequested) % HEAP_SIZE > heap_start)
			ret = NULL;
		else {
			ret = (void *)&xHeap.heap[heap_end + sizeRequested - HEAP_SIZE];
			heap_end += sizeRequested - HEAP_SIZE;
		}
	}
	else{
		ret = (void *)&xHeap.heap[heap_end + sizeRequested];
		heap_end += sizeRequested;
	}
	return ret;
}

/**
 * @brief: Returns the size of free heap
 */
uint_32 getHeapSize(){
	return (heap_end > heap_start)?(heap_end - heap_start):(heap_end + HEAP_SIZE - heap_start);
}
